package com.dianrui.agent.util;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;


import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;




public class MyUtil {

    public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private static Stack<Activity> mActivities = new Stack<>();
    private static MyUtil instance = null;

    public static MyUtil getInstance() {
        if (null == instance) {
            synchronized (MyUtil.class) {
                if (null == instance) {
                    instance = new MyUtil();
                }
            }
        }
        return instance;
    }

    //点下出动画
    public static void initViewAnimation(final View showView, boolean isshow, boolean istop) {

        float[] up2down;

        float[] down2up;

        if (istop) {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{0.0f, 0.0f};

        } else {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{1.0f, 0.0f};
        }

        if (isshow) {
            TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, down2up[0], Animation.RELATIVE_TO_SELF, down2up[1]);
            mShowAction.setDuration(500);
            showView.clearAnimation();
            showView.startAnimation(mShowAction);
        } else {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, up2down[0], Animation.RELATIVE_TO_SELF, up2down[1]);
            mHiddenAction.setDuration(500);
            mHiddenAction.setAnimationListener(new Animation.AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    showView.setVisibility(View.GONE);
                    showView.invalidate();
                }
            });

            showView.clearAnimation();
            showView.startAnimation(mHiddenAction);
        }
    }

    public static String stringForTime(long timeMs) {
        long totalSeconds = timeMs / 1000;
        long seconds = totalSeconds % 60;
        long minutes = (totalSeconds / 60) % 60;

        return new Formatter().format("%02d:%02d", minutes, seconds).toString();
    }

    /**
     * 将String类型的时间转换成long,如：12:01:08
     *
     * @param strTime String类型的时间
     * @return long类型的时间
     */
    public long convertStrTimeToLong(String strTime) {
        // TODO Auto-generated method stub
        String[] timeArry = strTime.split(":");
        long longTime = 0;
        if (timeArry.length == 2) {//如果时间是MM:SS格式
            longTime = Integer.parseInt(timeArry[0]) * 1000 * 60 + Integer.parseInt(timeArry[1]) * 1000;
        } else if (timeArry.length == 3) {//如果时间是HH:MM:SS格式
            longTime = Integer.parseInt(timeArry[0]) * 1000 * 60 * 60 + Integer.parseInt(timeArry[1]) * 1000 * 60 + Integer.parseInt(timeArry[0]) * 1000;
        }
        return SystemClock.elapsedRealtime() - longTime;
    }


    public static void initViewDownAnimation(final View showView, boolean isshow, boolean istop) {

        float[] up2down;

        float[] down2up;

        if (istop) {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{0.0f, 1.0f};

        } else {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{1.0f, 0.0f};
        }

        if (isshow) {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, up2down[0], Animation.RELATIVE_TO_SELF, up2down[1]);
            mHiddenAction.setDuration(100);
            mHiddenAction.setAnimationListener(new Animation.AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    showView.setVisibility(View.INVISIBLE);
                    showView.invalidate();
                }
            });

            showView.clearAnimation();
            showView.startAnimation(mHiddenAction);
        } else {
            TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, down2up[0], Animation.RELATIVE_TO_SELF, down2up[1]);
            mShowAction.setDuration(400);
            showView.clearAnimation();
            showView.startAnimation(mShowAction);
        }
    }


    public static String getAppInfo(Context context) {
        try {
            String pkName = context.getPackageName();
            String versionName = context.getPackageManager().getPackageInfo(pkName, 0).versionName;
            int versionCode = context.getPackageManager().getPackageInfo(pkName, 0).versionCode;
            return versionName;
        } catch (Exception e) {
        }
        return null;
    }


    //获取手机型号
    public static String getSystemModel() {
        return Build.MODEL;
    }

    //   获取手机品牌
    public static String getSystemBARND() {
        return Build.BRAND;
    }

    @SuppressLint("HardwareIds")
    public static String getUniqueId(Context context) {
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return toMD5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }

    public static String gpsToDistanceKM(double a, double b, double c, double d) {
        DecimalFormat df = new DecimalFormat("######0.00");
        float[] results = new float[1];
        Location.distanceBetween(a, b, c, d, results);
        return df.format(Double.valueOf(results[0] / 1000));
    }

    private static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }


    /*** 判断网络情况   有网络返回true，没网络返回false*/
    public static boolean isNetworkAvalible(Context context) {
        //检测API是不是小于23，因为到了API23之后getNetworkInfo(int networkType)方法被弃用
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //获得ConnectivityManager对象
            android.net.ConnectivityManager connMgr = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取WIFI连接的信息
            android.net.NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(android.net.ConnectivityManager.TYPE_WIFI);
            //获取移动数据连接的信息
            android.net.NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(android.net.ConnectivityManager.TYPE_MOBILE);
            //无线网连接和数据网连接都断开
            if (!wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
                return false;
            }
            //无线网连接和数据网连接一个
            return true;
            //API大于23时使用下面的方式进行网络监听
        } else {
            // 获得网络状态管理器
            android.net.ConnectivityManager connectivityManager = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                return false;
            } else {
                // 建立网络数组
                android.net.NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();
                if (net_info != null) {
                    for (int i = 0; i < net_info.length; i++) {
                        // 判断获得的网络状态是否是处于连接状态
                        if (net_info[i].getState() == android.net.NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }

    public static int getAppVersionCode(Context context) {
        return getAppVersionCode(context, context.getPackageName());
    }

    /**
     * 获取App版本码
     *
     * @param context     上下文
     * @param packageName 包名
     * @return App版本码
     */
    public static int getAppVersionCode(Context context, String packageName) {
        if (isSpace(packageName)) return -1;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? -1 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static boolean isSpace(String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static String getAppVersionName(Context context) {
        return getAppVersionName(context, context.getPackageName());
    }

    public static String getAppVersionName(Context context, String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }


    private static boolean isInstallMaps(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        List<String> packageNames = new ArrayList<>();
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    public synchronized void removeActivity(Activity activity) {
        if (mActivities.contains(activity)) {
            mActivities.remove(activity);
        }
    }

    public synchronized void clear() {
        int index = size() - 1;
        while (index >= 0) {
            Activity activity = mActivities.pop();
            removeActivity(activity);
            activity.finish();
            index--;
        }
    }

    public int size() {
        return mActivities.size();
    }

    /**
     * 设置背景
     * 在API16以前使用setBackgroundDrawable，在API16以后使用setBackground
     * API16<---->4.1
     *
     * @param view
     * @param drawable
     */
    public static void setBackgroundOfVersion(View view, Drawable drawable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //Android系统大于等于API16，使用setBackground
            view.setBackground(drawable);
        } else {
            //Android系统小于API16，使用setBackground
            view.setBackgroundDrawable(drawable);
        }
    }

//    public static void createPhotoChooseDialog(final int requestCode, final int maxSize, final Context context, final FunctionConfig functionConfig, final GalleryFinal.OnHanlderResultCallback listener) {
//        String[] stringItems = {"拍照", "相册"};
//        final ActionSheetDialog dialog = new ActionSheetDialog(context, stringItems, null)
//                .isTitleShow(false)
//                .itemTextColor(Color.parseColor("#000000"))
//                .setmCancelBgColor(Color.parseColor("#FFFFFF"))
//                .cancelText(Color.BLACK);
//        dialog.title("选择您的方式");
//        dialog.titleTextSize_SP(14f).show();
//        dialog.setOnOperItemClickL(new OnOperItemClickL() {
//            @Override
//            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
//                switch (position) {
//                    case 0:
//                        GalleryFinal.openCamera(requestCode, functionConfig, listener);
//                        dialog.dismiss();
//                        break;
//                    case 1:
//                        GalleryFinal.openGalleryMuti(requestCode, maxSize, listener);
//                        dialog.dismiss();
//                        break;
//                }
//            }
//        });
//
//    }

    /***
     * 格式化Double类型并保留scale位小数
     * 四舍五入
     *
     * @param doubleVal
     * @param scale     scale必须为大于0的正整数，不能等于0
     * @return
     */
    public static String formatBy2Scale(Double doubleVal, int scale) {
        if (null == doubleVal) {
            doubleVal = new Double(0);
        }
        StringBuffer sbStr = new StringBuffer("0.");
        for (int i = 0; i < scale; i++) {
            sbStr.append("0");
        }
        DecimalFormat myformat = new DecimalFormat(sbStr.toString());
        return myformat.format(doubleVal);
    }


    /**
     * 校验身份证
     *
     * @param idCard
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isIDCard(String idCard) {
        String REGEX_ID_CARD = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);

    }

    /**
     * 设置TabLayout线宽
     *
     * @param tabs
     * @param leftDip  左边距
     * @param rightDip  右边距
     */
    public static void setTabLayoutIndicator(TabLayout tabs, int leftDip, int rightDip) {
        if (tabs == null)
            return;
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            //通过反射得到tablayout的下划线的Field
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return;
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            //得到承载下划线的LinearLayout   //源码可以看到SlidingTabStrip继承得到承载下划线的LinearLayout
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return;
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
        //循环设置下划线的左边距和右边距
        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    public static synchronized String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //设置地图缩放级别
    public static void setMapStatus(MapView mapView, float zoom) {
        mapView.getMap().animateCamera(CameraUpdateFactory.zoomTo(zoom));
    }

    //获取地图缩放级别
    public static float getZoom(MapView mapView) {
        return mapView.getMap().getCameraPosition().zoom;
    }
}
